﻿#include "PriceFileToKItemFIle.h"
#include "MarketDataStream.h"
#include "Tools.h"
#include "MarketDataManager.h"
#include "CTPTime.h"
#include "SymbolDetail.h"
#include <QFile>

PriceFileToKItemFIle::PriceFileToKItemFIle(QObject *parent)
	: QObject(parent)
{
}

PriceFileToKItemFIle::~PriceFileToKItemFIle()
{
}

void PriceFileToKItemFIle::CompositingKItem(const QString &symbolName, time_t pDataTime)
{
	// 读取所有的价格
	tm pData = Tools::GetDateTimeFrmStamp(pDataTime);
	std::string pDataStr = Tools::DateToStr(pData);
	CompositingKItemByDay(symbolName, QString::fromLocal8Bit(pDataStr.c_str()));
}

void PriceFileToKItemFIle::CompositingKItem(const std::string &symbolName, const std::string &beginData, const std::string &endData)
{
	tm beginDataTM = Tools::DateStr2TM(beginData);
	tm endDataTM = Tools::DateStr2TM(endData);

	std::vector<std::string> dbNames;
	CTPTm::DateRangeToStringList(Tools::GetTimeStamp(beginDataTM), Tools::GetTimeStamp(endDataTM), dbNames);

	MDIO::Price priceStream;
	MData::KLineItem pframKItem;
	for (int i = 0; i < dbNames.size(); ++i)
	{
		std::deque<MData::PriceItem> pPrices;
		priceStream.GetAllPrice(dbNames.at(i), symbolName, pPrices);
		MarketDataManager mdManager;
		int pIndex = 0;
		for (std::deque<MData::PriceItem>::iterator it = pPrices.begin(); it != pPrices.end(); ++it)
		{
			//if (pIndex == 0)
			//{
			//	++pIndex;
			//	continue;
			//}
			mdManager.UpdateLocalKItem(symbolName, *it, pframKItem);
			++pIndex;
		}
	}
}

void PriceFileToKItemFIle::CompositingKItem(const QString &beginData, const QString &endData)
{
	std::list<std::string> symbolList;
	SymbolPackage::GetTheLastMainSymbolList(symbolList, Tools::GetCurrentTimeStamp());
	SymbolPackage::OrderSymbolReaderWriter orderSymbols;
	orderSymbols.GetSymbolList(symbolList);
	for (std::list<std::string>::iterator it = symbolList.begin(); it != symbolList.end(); ++it)
	{
		CompositingKItem(*it, beginData.toLocal8Bit().data(), endData.toLocal8Bit().data());
	}
}

bool PriceFileToKItemFIle::HasGenBaseKItem(const QString &symbolName, const QString &pDay)
{
	MDIO::KItem pItemGen;
	std::string baseKDir = pItemGen.GetKItemDir();
	QString qbaseKDir = QString::fromLocal8Bit(baseKDir.c_str());
	QString pdayKDir = qbaseKDir + pDay + '/';
	QString kfilePath = pdayKDir + symbolName + ".klin";
	QFile pFile(kfilePath);
	return pFile.exists();
}

void PriceFileToKItemFIle::CompositingKItemByDay(const QString &symbolName, const QString &pDay)
{
	MDIO::Price priceStream;
	std::string pDataStr = pDay.toLocal8Bit().data();
	std::deque<MData::PriceItem> pPrices;
	priceStream.GetAllPrice(pDataStr, symbolName.toLocal8Bit().data(), pPrices);
	MarketDataManager mdManager;
	MData::KLineItem pframKItem;
	for (std::deque<MData::PriceItem>::iterator it = pPrices.begin(); it != pPrices.end(); ++it)
	{
		mdManager.UpdateLocalKItem(symbolName.toLocal8Bit().data(), *it, pframKItem);
	}
	mdManager.SaveTheLastKItem();
}
